import { PageContainer } from '@ant-design/pro-layout';
import { Button, InputNumber, message, Space, Table } from 'antd';
import { FormattedMessage } from 'umi';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import { DrawerForm, ProFormText, ProFormSelect, ProFormDigit, ModalForm, ProFormUploadDragger } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { FileExcelOutlined, PlusOutlined } from '@ant-design/icons';
import { ProductType } from '../../../model';
import { productList, insertProduct, updateProduct,updateProductShelves, deleteProduct, exportProduct,lineList } from '../service';
import { exportFile, productMixOption,productPropertyOption,manufacturerOptionOnly, manufacturerOptionArray } from '@/utils/utils';
import { Spin } from 'antd';
import { Modal } from 'antd';
import { useEffect } from 'react';
export default (() => {

  const [showCreate, setShowCreate] = useState(false);
  const actionRef = useRef<ActionType>();
  const [spinningFlag, setSpinningFlag] = useState(false);
  const [showImport, setShowImport] = useState<boolean>(false);
  const [errorVisible, setErrorVisible] = useState<boolean>(false);
  const [errInfo, setErrInfo] = useState<any[]>([]);
  const [productLine,setProductLine]  = useState<any>({});
  const [showPrice, setShowPrice] = useState(false);
  const [record, setRecord] = useState<any>({});
  const [editableRowKeys, setEditableRowKeys] = useState<React.Key[]>([0,1,2,3,4,5,6,7,8,9]);
  const [priceData, setPriceData] = useState<any[]>([
    {priceLevel:'A级',price:0,key:0},{priceLevel:'B级',price:0,key:1},{priceLevel:'A-H2',price:0,key:2},{priceLevel:'B-H2',price:0,key:3},
    {priceLevel:'C-H2',price:0,key:4},{priceLevel:'A级达标',price:0,key:5},{priceLevel:'B级达标',price:0,key:6},{priceLevel:'A-H2达标',price:0,key:7},{priceLevel:'B-H2达标',price:0,key:8},{priceLevel:'C-H2达标',price:0,key:9}]);
  const [dataList,setDataList] = useState<any[]>([
    {id:'1',product_name:'双极抓取钳',product_standard:'MP00001',packing_unit:'个',minimum:20},
    {id:'12',product_name:'持针钳',product_standard:'MP00002',packing_unit:'个',minimum:1},
    {id:'13',product_name:'单极剪',product_standard:'MP00003',packing_unit:'个',minimum:1}
  ])
  const priceColumns:ProColumns[] = [
    {
      title: '价格等级',
      dataIndex: 'priceLevel',
      editable:false
    },
    {
      title: '单价（元）',
      dataIndex: 'price',
      valueType:'money',
      formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '必填'
          }]
        };
      },
      renderFormItem: (_:any, {
        type,
        defaultRender,
        formItemProps,
        fieldProps,
        record,
        ...rest
      }, form) => {
        return <InputNumber key={_.index+''}  min={0}  placeholder='请输入'/>;
      }
    },
  ]

  const errorColumn = [{
    title: '错误行',
    dataIndex: 'rownum'
  }, {
    title: '错误信息',
    dataIndex: 'errerMsg'
  }]; //表头信息以及表值设置

  const columns: ProColumns[] = [
  {
    title: '产品名称',
    dataIndex: 'product_name',
    valueType: 'select',
    width: 150,
    ellipsis:true,
  }, {
    title: '产品型号',
    width: 200,
    ellipsis:true,
    dataIndex: 'product_standard',
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '此项为必填项'
        }]
      };
    }
  }
  ,
  {
    title: '产品分类',
    width:100,
    dataIndex: 'productType',
    valueType:'select',
    renderText:()=>'A'
  },
  {
    title: 'model/机型',
    width:100,
    dataIndex: 'model',
    valueType:'select',
    valueEnum:{
      Si:'Si',
      Xi:'Xi',
      'Si&Xi':'Si&Xi'
    }
  },
  {
    title: '器械大类',
    width:130,
    dataIndex: 'productCategory',
    valueType:'select',
    renderText:()=>'一次性耗材'
  },
  ,{
    title: '售卖状态',
    dataIndex: 'sellStatus',
    width: 100,
    editable:false,
    valueType:'select',
    valueEnum:{
      '1':'在售',
      '2':'下架',
      '0':'缺货',
      '3':'在售关注型号'
    },
    renderText:()=>'在售'

  } , {
    title: '税率',
    hideInSearch: true,
    width: 80,
    dataIndex: 'taxRate',
    renderText: (taxRate:any) => {
      return '13%';
    }
  }
  ,{
    title: '有效期',
    dataIndex: 'lifespan',
    ellipsis:true,
    width: 100,
    hideInSearch:true,
    renderText:()=>'两年'
  },
  {
    title: '最小售卖单位',
    dataIndex: 'sellUnit',
    width: 120,
    hideInSearch: true,
    renderText:()=>'个'
  }, {
    title: '最小使用单位',
    dataIndex: 'usageUnit',
    width: 120,
    hideInSearch: true,
    renderText:()=>'个'
  }
  , {
    title: '个/包(可使用次数)',
    dataIndex: 'timesOfUsage',
    width: 150,
    hideInSearch: true,
    renderText:()=>'10'
  },
  
  // ,{
  //   title: '换算比率',
  //   dataIndex: 'ratio',
  //   width:120,
  //   editable:false,
  //   ellipsis:true,
  //   hideInSearch: true,
  // },

  // {
  //   title: '品牌/厂家',
  //   dataIndex: 'manufacturer',
  //   hideInSearch: true,
  //   ellipsis:true,
  // }, 
  {
    title: '最小起订量',
    dataIndex: 'minOrderNum',
    width: 100,
    hideInSearch: true,
  },
  {
    title: '注册证信息',
    width:200,
    dataIndex: 'certificateNum',
    ellipsis:true,
    hideInSearch: true,
  }, 
  {
    title: '备注',
    dataIndex: 'remark',
    width:200,
    ellipsis:true,
    hideInSearch: true,
  },
   {
    title: '操作',
    valueType: 'option',
    width:120,
    fixed: 'right',
    render: (text, record, _, action) => [<a key='editable' onClick={() => {
      action.startEditable?.(record.id);
    }}>
          编辑
        </a>,<a key='price' onClick={() => {
      
    }}>
          删除
        </a>]
  }];

  const onFileUpload = (info: any) => {
    if (info.file.status !== 'uploading') {}

    if (info.file.status === 'done') {
      if (info.file.response.errorCode === '200') {
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        actionRef.current?.reloadAndRest?.();
        setShowImport(false);
      } else {
        message.error('上传失败: ' + info.file.response.msg);
        setErrorVisible(true);
        setErrInfo(info.file.response.data);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  };

  const handleCancel = () => {
    setErrorVisible(false);
    setErrInfo([]);
  };

  const getProductLine = async()=>{
    var val = await lineList({})
    var map:any = {}
    val.data.forEach((item:any) => {
        map[item.id] = {text:item.name}
    });
    setProductLine(map)
  }

  const updateBatchProduct =async (flag:string,ids:any)=>{
    var param: any = {
      isShelves:flag,
      ids:  ids.join(',')
    };
    var val = await updateProductShelves(param);
    if (val.errorCode = 200) {
      message.success('设置成功')
      actionRef.current?.reloadAndRest?.()
    }else{
      message.error(val.errorMessage)
    }
  }

  useEffect(() => {
    getProductLine();

    return function cleanup() {};
  }, []);

  return <PageContainer>
    <ProTable<ProductType> actionRef={actionRef} headerTitle='产品列表' pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} scroll={{
      x: 1300
    }} 
    // request={(params, sorter, filter) => productList({ ...params,
    //   filter
    // })}
    dataSource={dataList}
     columns={columns} rowKey='id' search={{
      labelWidth: 120
    }} toolBarRender={() => [<Button type='primary' key='primary' onClick={() => {
      setShowCreate(true);
    }}>
          <PlusOutlined/> <FormattedMessage id='pages.searchTable.new' defaultMessage='新建'/>
        </Button>, <Button type='primary' key='import' onClick={async () => {
      setShowImport(true);
    }}>
       <FileExcelOutlined/>导入
      </Button>, <Button type='primary' key='export' onClick={async () => {
      setSpinningFlag(true);
      var val = await exportProduct({});

      if (val.errorCode === '200') {
        exportFile(val.data, '产品.xlsx');
      } else {
        message.error('导出失败');
      }

      setSpinningFlag(false);
    }}>
          <FileExcelOutlined/>导出
         </Button>]} toolbar={{
      settings: []
    }} editable={{
      type: 'multiple',
      onSave: async (values: any, record:any) => {
        record.select_price = undefined;

        // if (record.isTriggerGift === '否') {
        //   record.isTriggerGift = '0';
        // }

        // if (record.isTriggerGift === '是') {
        //   record.isTriggerGift = '1';
        // }

        var manufacturerData = manufacturerOptionArray();
        manufacturerData.forEach((item: any) => {
          if (item.label == record.manufacturer) {
            record.manufacturer = item.value;
          }
        });
        // record.productLineName = productLine[record.productLineId].text
        var val = await updateProduct(record);

        if (val.errorCode === '200') {
          message.success('更新成功');
          return true;
        } else {
          message.error('更新失败');
          return false;
        }
      },
      onDelete: async (value: any) => {
        var val = await deleteProduct({
          ids: value
        });

        if (val.errorCode === '200') {
          message.success('删除成功');
          return true;
        } else {
          message.error('删除失败');
          return false;
        }
      }
    }}
    // tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
    //   return (
    //     <Space size={16}>
    //       <a key="i2" style={{ marginLeft: 8 }} onClick={onCleanSelected}>
    //         取消选择
    //       </a>
    //       <a key="i1" onClick={()=>{
    //         updateBatchProduct("1",selectedRowKeys);
    //       }}>在售</a>
    //       <a key="i0" onClick={()=>{
    //         updateBatchProduct("0",selectedRowKeys);
    //       }}>下架</a>
    //     </Space>
    //   );
    // }}
    // rowSelection={{
    //   selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
    // }}
    />
      <DrawerForm title='产品创建' onVisibleChange={setShowCreate} visible={showCreate} onFinish={async (values: any) => {
          var val = await insertProduct(values);
          if (val.errorCode === '200') {
            message.success('提交成功');
            actionRef.current?.reloadAndRest?.();
            return true;
          } else {
            message.error(val.errorMessage);
            return false;
          }
    }}>
     <ProFormText name='product_name' label='产品名称' placeholder='请选择产品名称'  rules={[{
        required: true
      }]}/> 
           <ProFormText name='product_standard' label='产品型号' placeholder='请输入产品型号' rules={[{
        required: true
      }]}/>
    <ProFormSelect rules={[{
        required: true
      }]} name='productProperty' label='产品性质' placeholder='请选择产品性质' options={Object.keys(productPropertyOption()).map(item=>{return {"label":item,"value":item}})}/>

           <ProFormText name='packing_unit' label='单位' placeholder='请输入包装单位' rules={[{
        required: true
      }]}/>

        <ProFormDigit name='standard_price5' label='标准价' placeholder='请输入标准价'/>
         </DrawerForm>
    <ModalForm title='产品导入' onVisibleChange={v => {
      setShowImport(v);
    }} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} visible={showImport} onFinish={async (values: any) => {
      console.log(values);
      return true;
    }}>
             <div style={{
        margin: '.125rem 0 .25rem 0'
      }}><a href='/xwyl/attach/product.xlsx' download='产品模板.xlsx'><Button type='primary'> <FileExcelOutlined/>产品模板下载</Button></a></div>
            <ProFormUploadDragger label='选择excel上传' name='file' action='/xwyl/product/importProduct' fieldProps={{
        name: 'file',
        headers: {
          'authorization': (sessionStorage.getItem('token') as string)
        }
      }} max={1} onChange={onFileUpload}/>

         </ModalForm>

         <ModalForm title='价格维护' onVisibleChange={v => {
            setShowPrice(v);
          }} modalProps={{
            destroyOnClose: true,
            forceRender: true
          }} visible={showPrice} onFinish={async (values: any) => {
            console.log(values);
            return true;
          }}>
            <EditableProTable
                  style={{marginLeft:-20}}
                  headerTitle="远端通路导管"
                  value={priceData}
                  columns={priceColumns}
                  rowKey='id'
                  search={false}
                  key='key'
                  toolBarRender={() => []}
                  toolbar={{settings:[]}}
                  pagination={false}
                  recordCreatorProps={false}
                  editable={{
                    editableKeys:editableRowKeys,
                    type: 'multiple',
                    onChange: setEditableRowKeys,
                    actionRender: (row, config, defaultDoms) => {
                    return [];
                    }
                  }}
             />
         </ModalForm>
         <Modal visible={errorVisible} title='导入错误提示' width={800} footer={null} destroyOnClose={true} onCancel={handleCancel}>
          <Table dataSource={errInfo} style={{
        height: 400
      }} columns={errorColumn} pagination={false} rowKey='rownum'></Table>
        </Modal>
         <Spin spinning={spinningFlag} style={{
      transform: 'translate(-50%,-50%)',
      left: '50%',
      top: '50%',
      position: 'absolute'
    }}/>
  </PageContainer>;
});
